package com.qiantu.phone.ui.fragment;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.hjq.base.DensityUtils;
import com.hjq.http.listener.HttpCallback;
import com.hjq.widget.layout.SettingBar;
import com.hjq.widget.view.QMUIRadiusImageView;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.UserInfoBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.BuildConfig;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.SingleClick;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.TitleBarFragment;
import com.qiantu.phone.event.RefreshPushBannerSettingEvent;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.ui.activity.AboutAppActivity;
import com.qiantu.phone.ui.activity.BrowserActivity;
import com.qiantu.phone.ui.activity.DeviceGroupListActivity;
import com.qiantu.phone.ui.activity.HomeActivity;
import com.qiantu.phone.ui.activity.HomeManagerActivity;
import com.qiantu.phone.ui.activity.LingluCollegeActivity;
import com.qiantu.phone.ui.activity.MessageCenterActivity;
import com.qiantu.phone.ui.activity.PersonalDataActivity;
import com.qiantu.phone.ui.activity.SettingActivity;
import com.qiantu.phone.ui.activity.SmartControlActivity;
import com.qiantu.phone.ui.activity.TimeActivity;
import com.qiantu.phone.widget.viewmodel.EnergyConsumptionPresenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * time   : 2021/12/22
 * desc   : 我的 Fragment
 */
public final class MineFragment extends TitleBarFragment<HomeActivity> {

    private ImageView userMsgEdit;
    private ImageView userIcon;
    private TextView userName;
    private TextView deviceCount;
    private ImageView adImageView;
    private LinearLayout localNetTip;
    private TextView homeManage;
    private TextView controllerManage;
    private QMUIRadiusImageView ad;
    private SettingBar messageCenter;
    private SettingBar serviceCenter;
    private SettingBar lingLuSchool;
    private SettingBar aboutApk;
    private SettingBar settings;
    EnergyConsumptionPresenter energyConsumptionView;
    UserInfoBean userInfo;

    public static MineFragment newInstance() {
        return new MineFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.mine_fragment;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        //findViewById(R.id.local_net_tip).setVisibility(AppApplication.isLocalNet ? View.VISIBLE : View.GONE);
        energyConsumptionView = new EnergyConsumptionPresenter(this, findViewById(R.id.energy_consumption_ly));
        adImageView = findViewById(R.id.ad);
        setOnClickListener(R.id.user_msg_edit, R.id.user_icon, R.id.home_manage, R.id.controller_manage, R.id.message_center, R.id.ling_lu_school, R.id.about_apk, R.id.settings, R.id.device_group,R.id.time_record);
        userMsgEdit = findViewById(R.id.user_msg_edit);
        userIcon = findViewById(R.id.user_icon);
        userName = findViewById(R.id.user_name);
        deviceCount = findViewById(R.id.device_count);
        localNetTip = findViewById(R.id.local_net_tip);
        homeManage = findViewById(R.id.home_manage);
        controllerManage = findViewById(R.id.controller_manage);
        messageCenter = findViewById(R.id.message_center);
//        serviceCenter = findViewById(R.id.service_center);
        lingLuSchool = findViewById(R.id.ling_lu_school);
        lingLuSchool.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        aboutApk = findViewById(R.id.about_apk);
        settings = findViewById(R.id.settings);
    }

    @Override
    protected void initData() {
        getUserInfo();
    }

    @Override
    protected void onActivityResume() {
        super.onActivityResume();
    }

    @Override
    protected void onFragmentResume(boolean first) {
        super.onFragmentResume(first);
    }

    private void getUserInfo(){
        LLHttpManager.getUserInfo(this, new HttpCallback<HttpData<UserInfoBean>>(null){
            @Override
            public void onSucceed(HttpData<UserInfoBean> result) {
                super.onSucceed(result);
                userInfo = result.getData();
                AppApplication.getInstance().getLoginInfo().setUserInfo(userInfo);
                AppApplication.getInstance().updateLoginInfo(AppApplication.getInstance().getLoginInfo());
                updateView();
            }

            @Override
            public void onFail(Exception e) {
            }
        });
    }

    private void updateView(){
        if(getActivity() == null){
            return;
        }
        setAdImageView();
        if (AppApplication.getInstance().getLoginInfo().getUserInfo() != null){
            userInfo = AppApplication.getInstance().getLoginInfo().getUserInfo();
            GlideApp.with(getActivity())
                    .load(userInfo.getAvatar())
                    .placeholder(userIcon.getDrawable())
                    .error(userIcon.getDrawable())
                    .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                    .into(userIcon);
            userName.setText(userInfo.getNickName());
        }
        long size = LLDeviceDBManager.getInstance(getContext()).getAvailableDeviceCount();
        deviceCount.setText(getString(R.string.device_number, size));
        if(AppApplication.getInstance().getCurHouseInfo().getRoleType() == 2){
            findViewById(R.id.manage_line).setVisibility(View.GONE);
            findViewById(R.id.controller_manage_layout).setVisibility(View.GONE);
            messageCenter.setVisibility(View.GONE);
            findViewById(R.id.setting_device_group).setVisibility(View.GONE);
            findViewById(R.id.time_record).setVisibility(View.GONE);
        }else{
            findViewById(R.id.manage_line).setVisibility(View.VISIBLE);
            findViewById(R.id.controller_manage_layout).setVisibility(View.VISIBLE);
            messageCenter.setVisibility(View.VISIBLE);
            findViewById(R.id.setting_device_group).setVisibility(View.VISIBLE);
            findViewById(R.id.time_record).setVisibility(View.VISIBLE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshPushBannerSettingEvent(RefreshPushBannerSettingEvent event) {
        if(getActivity() == null){
            return;
        }
        setAdImageView();
    }

    public void setAdImageView(){
        if(AppApplication.getInstance().mSettingBean != null && AppApplication.getInstance().mSettingBean.getSetting().getInterfaceCustomization().isPushBanner()){
            GlideApp.with(getActivity())
                    .load(BuildConfig.APP_AD_BASE + "img_bg_advertising.png")
                    .into(new CustomTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            adImageView.setImageDrawable(resource);
//                            adImageView.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {

                        }
                    });
        }else{
            adImageView.setVisibility(View.GONE);
        }
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_msg_edit:
            case R.id.user_icon:
                startActivity(PersonalDataActivity.class);
                break;
            case R.id.message_center:
                startActivity(MessageCenterActivity.class);
                break;
            case R.id.home_manage:
                startActivity(HomeManagerActivity.class);
                break;
            case R.id.controller_manage:
                startActivity(SmartControlActivity.class);
                break;
//            case R.id.service_center:
//                int androidHeight = DensityUtils.getStatusBarHeight(getAttachActivity()) + getResources().getDimensionPixelSize(R.dimen.dp_16);
//                StringBuilder stringBuilder = new StringBuilder(BuildConfig.SERVER_CENTER_URL);
//                stringBuilder.append("?token=").append("'" + AppApplication.getInstance().getLoginInfo().getToken() + "'")
//                        .append("&houseId=").append("'" + AppApplication.getInstance().getCurrentHouseSerialNo() + "'")
//                        .append("&androidHeight=").append("'" + androidHeight + "'")
//                        .append("&phone=").append("'" + AppApplication.getInstance().getLoginInfo().getUserInfo().getPhone() + "'");
//                BrowserActivity.start(getContext(), stringBuilder.toString());
//                break;
            case R.id.ling_lu_school:
                startActivity(LingluCollegeActivity.class);
                break;
            case R.id.about_apk:
                startActivity(AboutAppActivity.class);
                break;
            case R.id.settings:
                SettingActivity.start(getContext());
                break;
            case R.id.device_group:
                Intent intent = new Intent(getContext(), DeviceGroupListActivity.class);
                intent.putExtra("viewType",1);
                getContext().startActivity(intent);
//                startActivity(DeviceGroupListActivity.class);
                break;
            case R.id.time_record:
                Intent intent1 = new Intent(getContext(), TimeActivity.class);
                startActivity(intent1);
                break;
        }
    }

    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        if(!isHidden()){
            getAttachActivity().getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarChangeIsDarkFont)).init();
            updateView();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!isHidden()){
            energyConsumptionView.getEnergyData();
            getAttachActivity().getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarChangeIsDarkFont)).init();
            updateView();
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}